package com.tz.oa.sysmanage.controller;

import com.tz.oa.sysmanage.entity.User;
import com.tz.oa.sysmanage.entity.UserInformation;
import com.tz.oa.sysmanage.entity.Userinfo;
import com.tz.oa.sysmanage.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService iUserService;


    @RequestMapping("/add")
    public String addUser(User user){
        Integer userid = iUserService.saveUser(user);
        return "main";
    }

    @ResponseBody//只能解析集合对象不包括String类型
    @RequestMapping("/select")
    public List<Userinfo> selectUser(){

        Userinfo user1=new Userinfo();
        user1.setUserId((long) 1);
        user1.setUserName("张三");
        user1.setAge(11);
        user1.setBirthday(new Date());

        user1.setLoginName("张三");
        user1.setPassword("123");
        user1.setSex(1);
        user1.setTvUpdate(new Date());

        Userinfo user2=new Userinfo();
        user2.setUserId((long) 1);
        user2.setUserName("李四");
        user2.setAge(11);
        user2.setBirthday(new Date());

        user2.setLoginName("张三");
        user2.setPassword("123");
        user2.setSex(1);
        user2.setTvUpdate(new Date());

        List<Userinfo> ls=new ArrayList<>();
        ls.add(user1);
        ls.add(user2);
        return ls;
    }


    @ResponseBody
    @RequestMapping("/testSpecialFormatter")
    public Map<String,String> testSpecialFormatter(@RequestBody @Validated Userinfo userinfo, BindingResult result){

        System.out.println(userinfo.toString());

        Map<String,String> map=new HashMap<>();
        if (result.hasErrors()){
            List<ObjectError> errors=result.getAllErrors();
            Integer a=1;
            for (ObjectError error:errors) {
                map.put("错误信息"+a,error.getDefaultMessage());
                a++;
            }
        }
        return map;
    }
    @ResponseBody
    @RequestMapping("/testform")
    public String testSpecialFormatter(@RequestBody @Validated UserInformation userInformation){

        System.out.println(userInformation.toString());

        int i=iUserService.insert(userInformation);

        String str="保存id:"+i+"成功！";

        return str;
    }

    @ResponseBody
    @RequestMapping("/selectAll")
    public List<User> selectAll(){
        List<User> userList = iUserService.selectAll();
        return userList;
    }
}
